using MongoDB.Driver;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Companies;
using Sustainalytics.Controversies.BusinessLogic;
using Sustainalytics.DataLayer;
using Sustainalytics.DataLayer.EsgRatings;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace Sustainalytics.Portfolios.BL.Tests.IntegrationTest
{

    public class PortfolioMatchingIntegrationTest
    {
        private readonly string _localDatabase = "mongodb://54.154.132.43:27017/ClientPlatform";

        private readonly string _stageDatabase = "mongodb://54.154.132.43:27017/ClientDW_A";

        private readonly string _stageScreening = "mongodb://54.171.12.91:27017/CompanySearchDW_A";

        private readonly IMongoCollection<CorporateData> _corporateDataCollection;

        private readonly ICustomPortfolioUpdateHandler _sut;

        private readonly PortfolioUserClaims _userClaimsFake = new PortfolioUserClaims
        {
            UserName = "teodor.bajan@sustainalytics.com",
            UserFullName = "Teodor Bajan",
            UserId = new Guid("4387c2a7-1eda-11e4-92ce-6c3be5be9f88"),
            AccountId = new Guid("528ea769-2d17-e411-92ce-6c3be5be9f98")
        };

        private readonly Dictionary<string, string> _serviceBusParams = new Dictionary<string, string>
            {
                { "ConnectionString", "Endpoint=sb://sust-test-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Dh/4Cq0qrOC7xOJFUYHLGJvQ6pqj4BuwjTS4HUjL6uQ=" },
                { "RegionEndpoint", "TT" },
                { "SessionId", "Portfolios" },
                { "TopicPath", "test-topic" },
            };

        public PortfolioMatchingIntegrationTest()
        {
            var userInputRepository = new RepositoryCollection<PortfolioUserInput>(this._stageDatabase);
            var portfolioDetailsRepository = new RepositoryCollection<PortfolioDetails>(this._stageDatabase);
            var portfolioMatchesRepository = new RepositoryCollection<Entities.PortfolioMatches>(this._stageDatabase);
            var portfolioRepository = new RepositoryCollection<Portfolio>(this._localDatabase);
            var esgInputFileRepository = EsgInputFileRepository.GetInstance(new FileRepository(this._localDatabase),
                                                                                                new RepositoryCollection<EsgInputFile>(this._localDatabase));

            this._companyDataRepository =
                new PlainMongoBl<CorporateData>(new RepositoryCollection<CorporateData>(this._stageDatabase));

            this._sut = new CustomPortfolioUpdateHandler(portfolioRepository, portfolioDetailsRepository, portfolioMatchesRepository,
                userInputRepository, esgInputFileRepository, new Replication.Publisher.ServiceBusPublisher( _serviceBusParams), 
                new CompanyMatchingLogic(_corporateDataCollection));

            this._sut.SetPortfolioMatching(
                new PortfolioMatching(
                    new CompanyMatchingLogic(_corporateDataCollection),
                    new CorporateDataUniversesLoader(MongoDB.Extensions.MongoFactory.GetCollectionFromDatabase<CorporateData>(this._stageDatabase))));
        }

        public IPlainBl<CorporateData> _companyDataRepository { get; set; }


        [Theory]
        [InlineData("3f0fbd57-ea0e-4fb4-a84c-94dda70d87b5")]
        public void Given_A_CompanyId_For_An_Identifier_Return(string companyId)
        {
            var result = this._sut.SearchForSecurities(
                string.Empty,
                "24568",
                this._userClaimsFake);

            Assert.False(result.Any(x => !x.IsValid));
        }


        [Fact]
        public void Given_A_CompanyList_For_A_Company_With_Multiple_Main_Securities_Returns_Null_security()
        {
            var result = this._sut.AddCompanyToPortfolio(
                new Guid("132cf407-0582-46bc-a95b-146ffd3deff4"),

                new Guid("be3e45d7-7367-426b-8ed5-a87f60006d92"),

                this._userClaimsFake);

            Assert.True(result.SavedWithErrors);
        }

        // For bug 6675
        [Theory]
        [InlineData("\"GB00B03MLX29\"")]
        [InlineData("XS0546218925")]
        [InlineData("NYSE:CVX")]
        public void Given_An_Identifier_For_A_Company_Portfolio_Matching_Is_Correct(string securityIdentifier)
        {
            // Arange
            string securityName = "security name test";

            var result = this._sut.SearchForSecurities(
                securityName,
                securityIdentifier,
                this._userClaimsFake);


            Assert.True(false, "Refactor this test due to modifications");
        }

        [Theory]
        [InlineData("XS0546218925")]
        [InlineData("NYSE:CVX")]
        [InlineData("1001491")]
        public void Given_An_Identifier_For_A_Security_Portfolio_Matching_Returns_No_Access_for_UserUniverses_Null(
            string securityIdentifier)
        {
            // Arange
            string securityName = "security name test";

            var result = this._sut.SearchForSecurities(
                securityName,
                securityIdentifier,
                this._userClaimsFake);

            Assert.True(false, "Refactor this test due to modifications");
        }


        [Fact]
        public void LivePortfolioMatching()
        {
            var testSut =
                new PortfolioMatching(
                    new CompanyMatchingLogic(
                       _corporateDataCollection), new CorporateDataUniversesLoader(MongoDB.Extensions.MongoFactory.GetCollectionFromDatabase<CorporateData>(this._stageDatabase)));
            testSut.GetMainSecurityForCompanies(
               new[]{ 1008431929, //
                1007976752,},
                _userClaimsFake);
        }

        [Fact]
        public void LivePortfolioMatching2()
        {

            var testSut = new CompanyMatchingLogic(MongoDB.Extensions.MongoFactory.GetCollectionFromDatabase<CorporateData>(this._localDatabase));
            var securitiesGrouping = testSut.GetCompaniesSearchByCompanyId(new[] {
                //new Guid("50c6557d-efea-4bc8-8aca-d2ab429fb252"),
                //new Guid("6c6845ff-4d9e-4f4d-b920-962af834ef0a")
                1008431929, //Credit Agricole
                1007976752 //Chevron Corp

            }).GroupBy(x => x.CompanyId);

            foreach (var securityGroup in securitiesGrouping)
            {
                var d = securityGroup.ToList();
                var result1 = d.GroupBy(x => x.CompanyId).Count();
                var result2 = d.All(s => s.CompanyName.Length > 3);
                var result4 = d.Where(x => x.CompanyName.Length < 3);
                var result3 = d.Where(a => a.CompanyId== 1008431929).GroupBy(a => new { a.CompanyId, a.CompanyName});
                var result = d.Count > 1;

                Assert.NotEqual(result1, 0);
                Assert.True(result2);
                Assert.NotEqual(result4.Count(), 0);
                Assert.NotEqual(result3.Count(), 0);
                Assert.True(result);

            }
        }
    }
}